package com.zwh.springcloud.zuul.config;

import com.alibaba.druid.pool.DruidDataSource;

import com.zwh.springcloud.zuul.custom.route.JDBCDynamicRouteLocator;
import com.zwh.springcloud.zuul.custom.route.RouteJdbcProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.netflix.zuul.filters.ZuulProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;

/**
 *
 * @author zwh
 * @date 2023-4-4
 */

@EnableConfigurationProperties(value = RouteJdbcProperties.class)
@Configuration(proxyBeanMethods = false)
public class RouteConfig {

    @ConditionalOnProperty(name = "zuul.custom.dynamic-route.enabled", havingValue = "true")
    @Bean
    public JDBCDynamicRouteLocator jdbcDynamicRouteLocator(ZuulProperties zuulProperties, ServerProperties server,
                                                           RouteJdbcProperties routeJdbcProperties){
        return new JDBCDynamicRouteLocator(server.getServlet().getContextPath(), zuulProperties,
                jdbcTemplate(routeJdbcProperties));
    }

    /**
     * 创建jdbcTemplate，不纳入Spring ioc容器中
     * @param routeJdbcProperties
     * @return
     */
    private JdbcTemplate jdbcTemplate(RouteJdbcProperties routeJdbcProperties) {
        // 使用druid数据源，可以动态配置数据库
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(routeJdbcProperties.getUrl());
        dataSource.setUsername(routeJdbcProperties.getUsername());
        dataSource.setPassword(routeJdbcProperties.getPassword());
        dataSource.setDriverClassName(routeJdbcProperties.getDriverClassName());

        dataSource.configFromPropety(routeJdbcProperties.getDruid());

        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
////        JdbcProperties.Template template = properties.getTemplate();
//        jdbcTemplate.setFetchSize(template.getFetchSize());
//        jdbcTemplate.setMaxRows(template.getMaxRows());
//        if (template.getQueryTimeout() != null) {
//            jdbcTemplate.setQueryTimeout((int) template.getQueryTimeout().getSeconds());
//        }
        // 单位秒
        jdbcTemplate.setQueryTimeout(10);
        return jdbcTemplate;
    }
}
